<?php

namespace App\Http\Controllers\Charge;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Income\IncomeCashController;
use App\Imports\Charge\ChargeImport;
use App\Models\Bus\BusDistribution;
use App\Models\Charge\Charge;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;

class ChargeController extends Controller
{
    public function chargeList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getChargeList($params)->orderByDesc('charging_end_at')->get()->toArray();
        $dataCount = $this->getChargeList($countParams)->count();

        return response()->formatJson(['chargeRecord' => $data, 'count' => $dataCount]);
    }

    public function getChargeList($params): \Illuminate\Database\Eloquent\Builder
    {
        $query = Charge::query();

        if (isset($params['license_plate_num'])) {
            $query->where('license_plate_num', 'like', '%' . $params['license_plate_num'] . '%');
        }

        if (isset($params['department']) && '-1' !== $params['department']) {
            $query->where('department', 'like', '%' . $params['department'] . '%');
        }

        if (isset($params['line']) && '-1' !== $params['line']) {
            $query->where('line', $params['line']);
        }

        if (isset($params['charging_end_at'])) {
            $charging_end_at = date('Y-m-d', strtotime($params['charging_end_at']));
            $query->whereDate('charging_end_at', $charging_end_at);
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 导入充电记录
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function importCharge(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $excelData = Excel::toArray(new ChargeImport, public_path() . $urlParse['path']);
        $fullData = $excelData[0];
        //新加标志参数用来二次确认是否导入数据 值为true或者false
        $mark = $request->input('mark');
        array_shift($fullData);

        $needFields = [
            'card_num'          => '卡号',
            'login_name'        => 'e充电登录名',
            'serials_num'       => '交易流水号',
            'VIN_num'           => 'VIN编码',
            'license_plate_num' => '车牌号/MAC编号',
            'user_num'          => '用户编号',
            'member_num'        => '成员名称',
            'member_dept'       => '成员所属机构',
            'department'        => '所属组织机构',
            'charge_type'       => '充电方式',
            'order_created_at'  => '订单创建时间',
            'order_status'      => '订单状态',
            'pay_type'          => '支付方式',
            'charging_pile_num' => '充电桩编号',
            'charging_station'  => '充电站',
            'trading_power'     => '交易电量/kwh',
            'trading_amt'       => '交易金额/元',
            'act_trading_amt'   => '实扣交易金额/元',
            'act_service_fee'   => '实扣服务费/元',
            'power_fee'         => '电费/元',
            'service_fee'       => '服务费/元',
            'discounted_amt'    => '优惠金额/元',
            'deduction_amt'     => 'E卡抵扣金额/元',
            'charging_start_at' => '充电开始时间',
            'charging_end_at'   => '充电结束时间',
            'is_invoiced'       => '是否开票',
        ];
        // 查找需要的数据，记录键名
        $importFileKeys = $fullData[0];
        if (!in_array('车牌号/MAC编号', $importFileKeys, true)) {
            return response()->formatJson(false, '未发现车牌号，请检查导入文件');
        }
        array_shift($fullData);

        $busDistributions = BusDistribution::all();
        $incomeCashController = new IncomeCashController();
        $keyData = [];
        foreach ($fullData as $k => $item) {
            foreach ($item as $key => $value) {
                $field = array_search($importFileKeys[$key], $needFields, true);
                if ($field) {
                    $keyData[$k][$field] = $value;
                }
            }
        }
        $data = [];
        $msg = [];
        // 整理数据，填充合并的单元格数据
        $importTime = date('Y-m-d H:i:s');
        foreach ($keyData as $row) {
            if ($row['license_plate_num']) {
                $row['license_plate_num'] = str_replace('陕G', '', $row['license_plate_num']);
            }
            if(!is_string($row['charging_end_at'])) {
                $row['charging_end_at'] = $this->transDateType($row['charging_end_at']);
            }
            if(!is_string($row['charging_start_at'])) {
                $row['charging_start_at'] = $this->transDateType($row['charging_start_at']);
            }
            if(!is_string($row['order_created_at'])) {
                $row['order_created_at'] = $this->transDateType($row['order_created_at']);
            }
            $chargeDate = date('Y-m-d', strtotime($row['charging_end_at']));
            $lastLine = $busDistributions
                ->where('date', '<=', $chargeDate)
                ->where('end_date', '>=', $chargeDate)
                ->firstWhere('license_plate_num', $row['license_plate_num']);
            $row['line'] = $lastLine->line ?? 999;
            $row['created_at'] = $importTime;
            if (!$mark) {
                // 检测数据是否重复
                $count = Charge::query()->whereDate('charging_end_at', $chargeDate)->count();
                if ($count) {
                    return response()->formatJson('', $chargeDate . '数据已存在，是否继续导入?');
                }
                //检测车牌号
                $busNumberArray = $busDistributions
                    ->where('date', '<=', $chargeDate)
                    ->where('end_date', '>=', $chargeDate)
                    ->pluck('license_plate_num')
                    ->all();
                $msgBus = $incomeCashController->checkBusNumber($row['license_plate_num'], $busNumberArray);
                if ($msgBus) {
                    $msg[] = $msgBus;
                }
            }
            $data[] = $row;
        }
        if ($msg) {
            $msgs = '';
            foreach ($msg as $items) {
                foreach ($items as $item) {
                    $msgs .= '<p> '.$item.' </p>'.PHP_EOL;
                }
            }
            return response()->formatJson('', $msgs);
        }

        foreach ($data as $item) {
            Charge::query()->updateOrCreate(
                [
                    'license_plate_num' => $item['license_plate_num'],
                    'charging_end_at' => $item['charging_end_at'],
                    'charging_start_at' => $item['charging_start_at'],
                ],
                $item
            );
        }
        return response()->formatJson(true, '导入成功');
    }

    public function transDateType($date)
    {
        return gmdate('Y-m-d H:i:s', ($date - 25569) * 3600 * 24);
    }
}
